package com.wuxianedu.http;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by TED on 2016/9/26.
 */
public class Download {

    public static  String path ;

    public static void down(String uri, Context context, ProgressDialog pd) throws IOException {
        URL url = new URL(uri);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        //设置请求超时
        conn.setConnectTimeout(5000);

        //    conn.connect();

        //请求成功
        if (conn.getResponseCode() == 200) {
            InputStream is = conn.getInputStream();

            pd.setMax(conn.getContentLength());
            if (sdCardExits(context)) {
                //拿到文件的名字
                String[] strings = uri.split("'?'");
                String[] strings1 = strings[0].split("/");
                String name = strings1[strings1.length - 1];
                Log.e("------", name);
                path = context.getExternalCacheDir().getPath() + File.separator + name;
                FileOutputStream fos = new FileOutputStream(path);

                byte[] b = new byte[1024];
                int count = 0;
                int value = 0;
                while((count = is.read(b))!=-1){
                    fos.write(b,0,count);
                    value += count;
                    pd.setProgress(value);
                }

            }
        }

    }


    public static boolean sdCardExits(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String path = context.getExternalCacheDir().getPath();
            Log.e("-----", path);
            File file = new File(path);
            if (!file.exists()) {
                return file.mkdirs();
            } else {
                return true;
            }
        }
        return false;
    }

}
